import fs from "fs-extra";
import path from "path";
import { toolchain } from "../toolchain.js";

export class TreeShake {
    public async lookUp(): Promise<void> {
        const pot: string[] = [];
        await this.removeEmptyDirs(path.join(toolchain.opts.projectRoot, 'Assets'), pot);
        await this.removeEmptyDirs(path.join(toolchain.opts.projectRoot, 'TsScripts'), pot);

        for (const d of pot) {
            console.log(d);
            // await new Cmd().run('svn', ['delete', root], { silent: true });
            await fs.remove(d);
            if (fs.existsSync(d + '.meta')) await fs.unlink(d + '.meta');
        }
    }

    private async removeEmptyDirs(root: string, pot: string[]): Promise<void> {
        const files = await fs.readdir(root);
        if (files.length == 0 || files.length == 2 && files[0] == 'model.txt' && files[1] == 'model.txt.meta') {
            pot.push(root);
            return;
        }
        for (const f of files) {
            const file = path.join(root, f);
            const fstat = await fs.stat(file);
            if (fstat.isDirectory()) await this.removeEmptyDirs(file, pot);
        }
    }

    public async removeUselessCodes(): Promise<void> {
        
    }
}
